<template>
  <div class="app-container">
    <div class="ces-main">



      <el-form :model="FormData" :inline="true" label-position="right" label-width="120px">


        <el-form-item v-if="this.StepSN == 0 || this.StepSN == -999" style="height:5px">

          <el-button type="primary" size="mini" icon="el-icon-tickets" @click="confirmData(0)">保存</el-button>
        </el-form-item>
        <!-- <el-form-item v-if="this.StepSN == 0" style="height:5px">
          <el-button type="primary" size="mini" icon="el-icon-check" @click="confirmData(1)">提交</el-button>
        </el-form-item> -->

        <el-form-item v-if="this.StepSN > 0" style="height:5px">
          <el-button type="primary" size="mini" icon="el-icon-tickets" @click="confirmData(0)">保存</el-button>
        </el-form-item>
        <el-form-item v-if="this.StepSN > 0" style="height:5px">
          <el-button type="primary" size="mini" icon="el-icon-check" @click="confirmData(3)">退回上一步</el-button>
        </el-form-item>
        <el-form-item v-if="this.StepSN > 0" style="height:5px">
          <el-button type="primary" size="mini" icon="el-icon-check" @click="confirmData(2)">审核</el-button>
        </el-form-item>
        <el-form-item style="height:5px">
          <el-button type="primary" size="mini" icon="el-icon-check" @click="handleAdd()">新增</el-button>
        </el-form-item>
        <el-form-item style="height:5px">
          <el-button type="primary" size="mini" icon="el-icon-check" @click="handleClose()">关闭</el-button>
        </el-form-item>


      </el-form>

      <span style="
            text-align: center;
            font-size: 20px;
            font-weight: bold;
            display: inline-block;
            width: 100%;
            padding: 3px 0 5px 0;
          ">
        <span>页面配置</span>
        <span style="margin-left: 10px">
          <svg-icon v-if="this.FormData.Status == 0 || this.FormData.Status == null" icon-class="Editing" />
          <svg-icon v-if="this.FormData.Status == 1" icon-class="ingAudit" />
          <svg-icon v-if="this.FormData.Status == 2" icon-class="Finish" />
        </span>
      </span>

      <el-form :model="FormData" label-width="90px">
        <Mian-Form ref="refFormData" labelWidth='100px' :FormData='FormData' :tableCols='FormCols' :StepSN='StepSN'
          @handleOpen="handleOpen"></Mian-Form>
      </el-form>


      <el-form :inline="true" :model="Search" class="demo-form-inline" size="mini">
      </el-form>

      <section class="ces-handle" sytle="display:flex">
        <el-button v-if="this.StepSN == 0 || this.StepSN == -999" type="primary" size="mini"
          @click="handleOpen('PrdNo')" icon="el-icon-tickets">添加数据</el-button>
        <el-button v-if="this.StepSN == 0 || this.StepSN == -999" type="primary" size="mini" @click="FunrRowsAddOne"
          icon="el-icon-tickets">添加一行</el-button>
      </section>






      <ces-table size='mini' :time="2050" high="130" ref="reftableData" :refs='reftableData' :isSelection='false'
        :tip="true" :isIndex='true' :isSearch='false' :isHandle='true' :ToolBarheight="360"
        :Isfunfail='this.StepSN == 0 || this.StepSN == -999 ? true : false' :IsfunEdit='true' :funEditName='BOM'
        :StepSN=this.StepSN :WFStepSN='WFStepSN' :tableData='tableData' :tableCols='tableCols' @handleDelete="delData"
        @handleEdit='handleEdit' @handrowclick="handrowclick" @handleEditWin="handleEditWin">
      </ces-table>

    </div>


    <!-- <el-main style="margin: 1px 10px">
      <span class="blueColor" style="font-size: 15px; font-weight: blod; padding: 10px">审核明细：</span>
      <el-timeline :reverse="true" ref="ListLog" :model="ListLog">
        <el-timeline-item v-for="(activity, index) in ListLog" :key="index" :timestamp="activity.CreateDateTime">
          {{ activity.Remark }}
        </el-timeline-item>
      </el-timeline>
    </el-main> -->

    <el-dialog v-if="dialogFormVisible" :visible.sync="dialogFormVisible" :title="添加" width="80%">
      <el-form :model="name" label-width="80px" label-position="left">
        <v-FormOpen :ParmType="ParmType" :FormDataInterID=420 :SearchData="Search"
          @FunRowAdd="FunrRowsAdd"></v-FormOpen>
      </el-form>
    </el-dialog>


    <el-dialog v-if="dialogVisibleTwo" :visible.sync="dialogVisibleTwo" :title="编辑" width="800px">
      <el-form :model="name" label-width="80px" label-position="left">
        <Mian-Form ref="refFormData" labelWidth='100px' :FormData='saveConfigurationDate' :tableCols='FieldDataCols'
          :StepSN='StepSN' @handleOpen="handleOpen"></Mian-Form>
      </el-form>
      <el-button type="primary" @click="saveConfiguration">保存</el-button>
      <el-button type="primary" @click="close">关闭</el-button>
    </el-dialog>




    <!-- <el-dialog
              v-if="dialogVisible"
              :visible.sync="dialogVisible"
              :title="销售订单"
              :fullscreen=true
              
              width="80%"
            >
              <el-form :model="name" label-width="80px" label-position="left">
                
              </el-form>
            </el-dialog> -->



  </div>
</template>

<script>


//引入组件

import cesTable from "../Common//table.vue";
import vFormOpen from "../Common/FormOpen";
import SearchForm from "../Common//Search.vue";
import MianForm from "../Common//form.vue";
import { PrintDate } from "@/api/Print";
import { funDownload, getDataList, GetTableColsData, GetFormColsData } from "@/api/Common";
import { UpdateForm, DeleteRow, MRPData, IsPrintForm, PageAutoDeletRow, FieldDataUpdate, GetDictDetail } from '@/api/System';


export default {
  name: "PageAutoForm",
  props: {
    inputName: String,
    required: true,
  },

  data() {
    //表单查询一般分为input，下拉框，和日期，下面是下拉框时的设置下拉信息的情况，我的项目没有用到，但是留着方便看

    return {
      AppCode: 'A05',
      configuration: null,
      labelPosition: 'top',
      formLabelAlign: {
        InterID: '',
        FieldName: '',
        region: '',
        type: '',
        type: '',
        type: ''
      },
      dialogVisibleTwo: false,
      saveConfigurationDate: [],
      MenuCode: "A050302",
      tableData: [],//表格数据
      FormData: [],//表格数据
      FormCols: [],//表头数据
      tableCols: [],//表格列数据
      FieldDataCols: [],
      StepSN: -1,
      WFStepSN: '0',
      billID: null,
      CompanyAppCode: "",
      ListLog: [],
      IsfunEdit: false,
      Search: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 13, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "420", // 表编号  根据Controller中对应的表编号
        jsWhere: "", // 自定义条件
        AppCode: 'A05'
      },

      cities: [
        {
          value: "0",
          label: "草稿",
        },
        {
          value: "1",
          label: "审核中",
        },
        {
          value: "2",
          label: "结案",
        },
        {
          value: "3",
          label: "作废",
        },
      ],
      SearchDialog: false,
      DialogBtnMargin: 0,
      dialogVisible: false,
      dialogFormVisible: false,

      ParmType: "",
      ProWhere: " and IDXI='A01'",
      PrdNo: null,

    }
  },

  components: { //引入组件后注册组件
    cesTable,
    vFormOpen,
    SearchForm,
    MianForm


  },
  mounted() {

    this.getTableCols()
    this.getDataList()


  },
  methods: {

    close() {
      this.dialogVisibleTwo = false
    },
    async saveConfiguration() {
      let result = await FieldDataUpdate({
        IsPostBack: true,
        HeadDate: JSON.stringify(this.saveConfigurationDate),
        InterID: this.saveConfigurationDate.InterID,
        FieldName: this.saveConfigurationDate.FieldName
      })

      if (result.code === 20000) {

        this.dialogVisibleTwo = false
        this.$notify({
          title: result.msg,
          dangerouslyUseHTMLString: true,
          message: "",
          type: "success",
        });
      }

    },

    handleClose(done) {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    },


    //读取列配置
    async getTableCols() {
      this.tableCols = [];
      this.FormCols = [];

      const resCols = await GetFormColsData({ InterID: "1583" });
      this.FormCols = resCols.data;

      const res = await GetTableColsData({ InterID: "5" });
      this.tableCols = res.data;

      const Fieldres = await GetTableColsData({ InterID: "422" });
      this.FieldDataCols = Fieldres.data;
      // console.log(this.FieldDataCols);

    },

    async getDataList() {
      if (this.inputName == null) {
        this.inputName = this.$route.query.billID;
      }
      const result = await UpdateForm({
        billID: this.inputName,
        IsPostBack: false,
      });

      this.FormData = result.data1.Table[0];
      // this.FormData.AppCode = this.AppCode
      this.tableData = result.data2;

      this.StepSN = result.StepSN;
      // debugger


    }, OpenFindForm() {
      //打开搜索框
      this.SearchDialog = true;
      //计算外边距
      console.log(this.$refs.searchDialog.offsetHeight);
      this.DialogBtnMargin = this.$refs.searchDialog.offsetHeight - 40;
    }, async confirmData(submit) {
      // 提交数据，需要修改

      const Fresult = true;




      if (submit == 1) {


        let flag1 = this.$refs['reftableData'].validateForm();

        let flag = this.$refs['refFormData'].validateForm();






        if (flag == false || flag1 == false) {
          this.$notify({
            title: "不能提交",
            dangerouslyUseHTMLString: true,
            message: "不可为空，不能提交",
            type: "error",
          });
          Fresult = false;
          return false;

        }

        if (this.tableData.length <= 0) {
          this.$notify({
            title: "不能提交",
            dangerouslyUseHTMLString: true,
            message: "行没有数据，不能提交",
            type: "error",
          });
          Fresult = false;
          return false;

        }

      }

      let options = "保存中...";

      if (submit == 1) {
        options = "提交中...";
      } else if (submit == 2) {
        options = "审批中...";
      } else if (submit == 3) {
        options = "退回中...";
      }

      const loading = this.$loading({
        lock: true,
        text: options,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      if (Fresult) {
        const result = await UpdateForm({
          HeadDate: JSON.stringify(this.FormData),
          BodyDate: JSON.stringify(this.tableData),
          billID: this.FormData.InterID,
          IsPostBack: true,
          submit: submit,
        });
        // alert(this.FormData.InterID)
        loading.close();
        this.FormData = result.data1.Table[0];
        this.tableData = result.data2;
        //this.ListLog = result.ListLog;
        this.StepSN = result.StepSN;
        //this.CompanyAppCode = result.CompanyAppCode;
        this.tableData.forEach((row, i) => { row.Sort = i })

        if (result.code === 20000) {

          this.dialogVisible = false;
          this.$notify({
            title: result.msg,
            dangerouslyUseHTMLString: true,
            message: "",
            type: "success",
          });


          this.$router.push({
            path: "/System/PageAutoForm",
            query: { billID: this.FormData.InterID, IsPostBack: false },
          });
          //   this.roles = [];
        } else {
          this.$notify({
            title: result.msg,
            dangerouslyUseHTMLString: true,
            message: "",
            type: "error",
          });
        }
      }
    },
    handleOpen(name) {

      this.dialogFormVisible = true;
      if (name == "PrdNo") {
        this.ParmType = "PrdNo"; //传入参数
        this.dialogFormVisible = true;
      }
    },
    // FunrRowsAdd: function (Rows, ParmType) {
    async FunrRowsAdd(Rows, ParmType) {
      this.FormData.AppCode = this.AppCode
      // this.FormData
      // debugger
      //添加人员
      this.multipleTable = Rows[0];
      // console.log(this.multipleTable)

      if (ParmType == "PrdNo") {
        // console.log(22222222222222);
        let DictDetail = await GetDictDetail({
          ObjectName: this.multipleTable.ObjectName,
          AppCode: this.AppCode
        })
        this.FormData.SaveTabelName = this.multipleTable.ObjectName
        // alert(JSON.stringify(this.multipleTable.ObjectName))
        // for (let v of DictDetail.data1) {
        for (let i = 0; i < DictDetail.data1.length; i++) {
          let row = {
            FieldType: 0,
            WFStepSN: null,
            IsNull: 0,
            IsWrite: 1,
            IsSearch: null,
            Visible: true,
            Sort: null,
            FormatData: null,
            SensiTiveData: null,
            GroupIndex: null,
            CustomHtml: null,
            IsColumnToRow: null,
            IsOrderBy: null,
            IsFormQuery: null,
            IsLocked: null,
            Decimaler: null,
            DefaultValue: null,
            Disable: null,
            ColumnPivot: null,
            AllowTotal: null,
            FieldName: DictDetail.data1[i].FieldName,
            Width: 120,
            FieldText: DictDetail.data1[i].FieldDesc,
          };

          this.tableData.push(row);
        }
        //过滤
        const uniqueIds = new Set(this.tableData.map(item => item.FieldName));
        let unique = []
        for (let item of uniqueIds) {
          for (let j = 0; j < this.tableData.length; j++) {
            if (item == this.tableData[j].FieldName) {
              unique.push(this.tableData[j])
              break
            }
          }
        }
        this.tableData = unique
        // console.log(this.tableData)
        // debugger
        this.tableData.forEach((row, i) => { row.Sort = i })
        // this.multipleTable = v;

        // console.log(ce);
        // }

        this.dialogFormVisible = false;
      }


    },

    async FunrRowsAddOne(Rows, ParmType) {
      // for (let i = 0; i < 1; i++) {
      var rowOne = {
        FieldType: 0,
        WFStepSN: null,
        IsNull: 0,
        IsWrite: 1,
        IsSearch: null,
        Visible: true,
        Sort: null,
        FormatData: null,
        SensiTiveData: null,
        GroupIndex: null,
        CustomHtml: null,
        IsColumnToRow: null,
        IsOrderBy: null,
        IsFormQuery: null,
        IsLocked: null,
        Decimaler: null,
        DefaultValue: null,
        Disable: null,
        ColumnPivot: null,
        AllowTotal: null,
        FieldName: null,
        Width: 120,
        FieldText: null,
      };
      this.tableData.push(rowOne);
      // this.dialogFormVisible = false;
      // }
    },

    async handleEdit(scope) {
      // 修改

      this.dialogVisibleTwo = true
      let Configuration = await FieldDataUpdate({
        InterID: scope.row.InterID,
        FieldName: scope.row.FieldName,
        IsPostBack: false,
      })

      this.saveConfigurationDate = Configuration.data.Table[0];
      this.saveConfigurationDate.InterID = scope.row.InterID;
      this.saveConfigurationDate.FieldName = scope.row.FieldName;


    },
    handrowclick(row) {
      this.billID = row.InterID;
      //this.PrdNo = row.PrdNo;
    },
    delData({ $index, row }) {
      this.$confirm('删除操作, 是否继续?', '提示', {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      })
        .then(async () => {

          // console.log(11111111);
          this.tableData.splice($index, 1);



          if (row.FieldName == null) {
            return false;
          }

          const result = await DeleteRow({
            FieldName: row.FieldName,
            InterID: this.FormData.InterID,
            IsPostBack: false,
          });

          this.$message({
            type: "success",
            message: result.msg,
          });

        })
        .catch((err) => {

          console.error(err);
        });
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .EditObjs-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 5px;
  }
}

.searchDialog ::v-deep .el-dialog__header {
  background: #409eff;
}

.searchDialog ::v-deep .el-dialog__title {
  color: #fff;
}

.searchDialog ::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.infoColor {
  font-weight: bold;
  color: #909399;
}

.redColor {
  font-weight: bold;
  color: red;
}

.blueColor {
  font-weight: bold;
  color: #409eff;
}

.orangeColor {
  font-weight: bold;
  color: orange;
}

.greenColor {
  font-weight: bold;
  color: #67c23a;
}
</style>